//
//  YearMonthDayPickerView.m
//  


#import "YearMonthDayPickerView.h"

#define kBottomFixHeight  (IS_IPhoneX_All ? kHeight_BottomSafe : 20)

#define kPickerHeight    (60 + 240 + 10 + 48 + kBottomFixHeight)

#define kPickerRowHeight 50

@interface YearMonthDayPickerView () <UIPickerViewDataSource,UIPickerViewDelegate>

@property (nonatomic) UIView *wholeView;

@property (nonatomic) NSMutableArray *yearArray,*monthArray,*dayArray;

@property (nonatomic) NSInteger currentYear,currentMonth,currentDay;

@property (nonatomic) NSString *selectDateString,*selectYearStr,*selectMonthStr,*selectDayStr;

@property (nonatomic) NSInteger originYear;

@property (nonatomic) UIPickerView *pickView;

@end

@implementation YearMonthDayPickerView

- (instancetype)initWithFrame:(CGRect)frame withCurrentSelectYearMonthDayString:(NSString *)dateString withkOriginYear:(NSInteger)originYear{

    self = [super initWithFrame:frame];
    
    if (self) {
    
        self.backgroundColor = kShadowViewColor;
        
        self.selectDateString = dateString;
    
        self.originYear = originYear;
        
        [self configView];
        
    }
    return self;
}

#pragma mark - Configuration
- (void)configView {
    
    self.yearArray = [[NSMutableArray alloc]init];
    
    self.monthArray = [[NSMutableArray alloc]init];
   
    self.dayArray = [[NSMutableArray alloc] init];
    
    NSArray *dateArray = [self.selectDateString componentsSeparatedByString:@"/"];
    
    if (dateArray.count < 3) {
        self.selectDateString = [NSString currentDateWithFormat:@"yyyy/MM/dd"];
        dateArray = [self.selectDateString componentsSeparatedByString:@"/"];
    }
    for (int i =0; i<dateArray.count; i++) {
        if (PMStringIsEmpty(dateArray[i])) {
            self.selectDateString = [NSString currentDateWithFormat:@"yyyy/MM/dd"];
            dateArray = [self.selectDateString componentsSeparatedByString:@"/"];
            break;
        }
    }
    
    
    [self getCurrentDate];
    
    [self setUpYearArray];
    
    [self setUpMonthArray];
    
    [self getDaysfromYear:[dateArray[0] integerValue]  andMonth:[dateArray[1] integerValue]];

    
    self.wholeView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight, kScreenWidth, kPickerHeight)];
    self.wholeView.backgroundColor = kWhiteColor;
    [self addSubview:self.wholeView];
    self.wholeView.layer.mask = [NSString UIBezierPathWithRect:self.wholeView.bounds withCorners:UIRectCornerTopLeft|UIRectCornerTopRight withRadiu:CGSizeMake(14, 14)];
    
    UILabel *titleLab = [UILabel createLabel:[UIFont fontWithName:kFuturaMedium size:16] color:kBlackColor];
    [self.wholeView addSubview:titleLab];
    titleLab.textAlignment  = 1;
    titleLab.frame = CGRectMake(0, 20, self.wholeView.width, 20);
    titleLab.text = ASLocalizedString(@"Date Selection");
    
    UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(self.wholeView.width - 10 - 20, 5, 20, 20)];
    [cancelBtn setImage:[UIImage imageNamed:@"icon_cancel"] forState:UIControlStateNormal];
    [cancelBtn setImage:[UIImage imageNamed:@"icon_cancel"] forState:UIControlStateSelected];
    [cancelBtn setImage:[UIImage imageNamed:@"icon_cancel"] forState:UIControlStateHighlighted];
    [cancelBtn addTarget:self action:@selector(hideBottomView) forControlEvents:UIControlEventTouchUpInside];
    [self.wholeView addSubview:cancelBtn];
    
    
    UIButton *sureButton = [[UIButton alloc]init];
    sureButton.frame = CGRectMake(30, self.wholeView.height - 48 - kBottomFixHeight, kScreenWidth - 60, 48);
    [sureButton setTitle:@"Confirming" forState:UIControlStateNormal];
    [sureButton setTitleColor:kWhiteColor forState:UIControlStateNormal];
    sureButton.titleLabel.font = [UIFont fontWithName:kFuturaMedium size:15];
    [sureButton setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateNormal];
    [sureButton addTarget:self action:@selector(clickConfirmBtn) forControlEvents:UIControlEventTouchUpInside];
    sureButton.layer.cornerRadius = 24;
    sureButton.layer.masksToBounds = YES;
    sureButton.backgroundColor = kButtonDefaultColor;
    [self.wholeView addSubview:sureButton];
    [sureButton setImgRightTitltLeft:10];
    
    
    UIPickerView *pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 60, kScreenWidth, 240)];
    pickerView.delegate = self;
    pickerView.dataSource = self;
    self.pickView = pickerView;
    pickerView.backgroundColor = [UIColor whiteColor];
    [self.wholeView addSubview:pickerView];
    
    if (dateArray.count == 3) {
        [pickerView selectRow:[self.selectYearStr integerValue] - self.originYear inComponent:2 animated:YES];
        [pickerView selectRow:[self.selectMonthStr integerValue] - 1 inComponent:1 animated:YES];
        [pickerView selectRow:[self.selectDayStr integerValue] - 1 inComponent:0 animated:YES];
        
    }
    
}

- (void)getCurrentDate {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy/MM/dd"];
    NSString *currentDateStr = [formatter stringFromDate:[NSDate date]];
    
    NSArray *dateArray = [currentDateStr componentsSeparatedByString:@"/"];
    if (dateArray.count == 3) {
        self.currentYear =   [dateArray[0] integerValue];
        self.currentMonth =  [dateArray[1] integerValue];
        self.currentDay =    [dateArray[2] integerValue];
    }
    self.selectYearStr = [NSString stringWithFormat:@"%ld",(long)self.currentYear];
    self.selectMonthStr = [NSString stringWithFormat:@"%ld",(long)self.currentMonth];
    self.selectDayStr = [NSString stringWithFormat:@"%ld",(long)self.currentDay];
    
    NSArray *getDateArray = [self.selectDateString componentsSeparatedByString:@"/"];
    if (getDateArray.count == 3) {
        
        self.selectYearStr = getDateArray[0];
        self.selectMonthStr = getDateArray[1];
        self.selectDayStr = getDateArray[2];
        
    }
   
}


- (void)setUpYearArray {
    [self.monthArray removeAllObjects];
    for (NSInteger i = self.originYear; i <= self.currentYear ; i++) {
        NSString *yearStr = [NSString stringWithFormat:@"%ld",(long)i];
        [self.yearArray addObject:yearStr];
    }
}

- (void)setUpMonthArray {

    [self.monthArray removeAllObjects];
    NSInteger nowYear = [[NSString currentDateWithFormat:@"yyyy"] integerValue];
   
    if ([self.selectYearStr isEqualToString:[NSString stringWithFormat:@"%ld",nowYear]]) {
        
        for (NSInteger i = 1 ; i <= self.currentMonth; i++) {
            
            NSString *monthStr = [NSString stringWithFormat:@"%ld",(long)i];
            
            if (i <= 9) {
                monthStr = [NSString stringWithFormat:@"%@%ld",@"0",(long)i];
            }
            
            [self.monthArray addObject:monthStr];
            
        }
        
    }
    else {
        
        for (NSInteger i = 1 ; i <= 12; i++) {
            
            NSString *monthStr = [NSString stringWithFormat:@"%ld",(long)i];
            
            if (i <= 9) {
                monthStr = [NSString stringWithFormat:@"%@%ld",@"0",(long)i];
            }
            
            [self.monthArray addObject:monthStr];
            
        }
        
    }
    
}

- (void)showBottomView {
    kWeakSelf
    [UIView animateWithDuration:0.25 animations:^{
        weakSelf.wholeView.frame = CGRectMake(0, kScreenHeight - kPickerHeight, kScreenWidth, kPickerHeight);
     } completion:^(BOOL finished) {}];
}

- (void)hideBottomView{
    kWeakSelf
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.wholeView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kPickerHeight);
     } completion:^(BOOL finished) {
         [self removeFromSuperview];
     }];
}

#pragma mark - UIPickerViewDataSource UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
    
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.dayArray.count;
    }
    else if (component == 1) {
        return self.monthArray.count;
    }
    return self.yearArray.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        return self.dayArray[row];
    }
    else if (component == 1) {
        return self.monthArray[row];
    }
    return self.yearArray[row];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    
    UILabel *pickerLabel = (UILabel *)view;
    
    if (!pickerLabel){
        pickerLabel = [UILabel createLabel:[UIFont fontWithName:kFuturaMedium size:15] color:[UIColor colorWithHexString:@"#6C6C6C"]];
        pickerLabel.textAlignment = 1;
    }
    
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    
    NSInteger selR = [self.pickView selectedRowInComponent:component];

    if (selR == row) {
        pickerLabel.textColor  = kButtonDefaultColor;
    }
    else{
        pickerLabel.textColor  = [UIColor colorWithHexString:@"#6C6C6C"];
    }
   
    
    
    return pickerLabel;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return kPickerRowHeight;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        self.selectDayStr = self.dayArray[row];
    }
    else if (component == 1) {
        self.selectMonthStr = self.monthArray[row];
    }
    else if (component == 2){
        self.selectYearStr = self.yearArray[row];
        [self setUpMonthArray];
    }
    
    
    if (component == 2 || component == 1) {
        [self getDaysfromYear:[self.selectYearStr integerValue] andMonth:[self.selectMonthStr integerValue]];
        if (self.dayArray.count < [self.selectDayStr integerValue]) {
            self.selectDayStr = [NSString stringWithFormat:@"%ld",self.dayArray.count];
        }
    }
    
    [pickerView reloadAllComponents];
    
}

- (NSInteger)getDaysfromYear:(NSInteger)year andMonth:(NSInteger)month{
    
    NSInteger num_year  = year;
   
    NSInteger num_month = month;
    
    BOOL isrunNian = num_year%4==0 ? (num_year%100==0? (num_year%400==0?YES:NO):YES):NO;
   
    switch (num_month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:{
            [self getDayNumArr:31];
            return 31;
        }
            break;
        case 4:
        case 6:
        case 9:
        case 11:{
            [self getDayNumArr:30];
            return 30;
        }
            break;
        case 2:{
            if (isrunNian) {
                [self getDayNumArr:29];
                return 29;
            }else{
                [self getDayNumArr:28];
                return 28;
            }
        }
            break;
        default:
            break;
    }
    return 0;
}

- (void)getDayNumArr:(NSInteger)num{
    [self.dayArray removeAllObjects];
    
    
    NSInteger nowYear = [[NSString currentDateWithFormat:@"yyyy"] integerValue];
    NSInteger nowMonth = [[NSString currentDateWithFormat:@"MM"] integerValue];
    if ([self.selectYearStr integerValue] == nowYear && [self.selectMonthStr integerValue] == nowMonth) {
        num = [[NSString currentDateWithFormat:@"dd"] integerValue];
    }
    
    
    
    for (int i=1; i<=num; i++) {
        [self.dayArray addObject:[NSString stringWithFormat:@"%02d",i]];
    }
}

 
#pragma mark - clickConfirmBtn
- (void)clickConfirmBtn{
    
    if (_callBackSelectDateBlock) {
        _callBackSelectDateBlock([NSString stringWithFormat:@"%@/%@/%@",esString(self.selectYearStr),esString(self.selectMonthStr),esString(self.selectDayStr)]);
    }
    
    [self hideBottomView];
    
}



@end


